package fun.lifepoem.core.utils;

import fun.lifepoem.core.domain.FileSecureEntity;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author Yiwyn
 * @create 2023/3/1 20:27
 */
public class SecureUtils {

    private static final BasicTextEncryptor encryptor = new BasicTextEncryptor();

    public static final String SPACER = ":";
    public static final String PASS_SPACER = "-";

    static {
        encryptor.setPassword("yiwyn");
    }

    /**
     * 加密
     *
     * @param clearText 明文
     * @return 密文
     */
    public static String encode(String clearText) {
        String encrypt = encryptor.encrypt(clearText);
        return encrypt;
    }


    /**
     * 加密文件分享信息
     *
     * @param secureEntity 文件分享信息实体
     * @return
     */
    public static String encode(FileSecureEntity secureEntity) {

        String clearText = secureEntity.getFileId() + SPACER + secureEntity.getExpiryTime() + SPACER + secureEntity.getExpiryTime();
        String encode = encode(clearText);

        return encode;
    }

    /**
     * 解密
     *
     * @param cipherText 密文
     * @return 明文
     */
    public static String decode(String cipherText) {
        String decrypt = encryptor.decrypt(cipherText);
        return decrypt;
    }


    /**
     * 将密文解密到实体信息
     *
     * @param cipherText 密文
     * @return 文件信息
     */
    public static FileSecureEntity decodeToEntity(String cipherText) {
        String decode = decode(cipherText);

        String[] results = decode.split(SPACER);

        FileSecureEntity entity = new FileSecureEntity();
        entity.setFileId(results[0]);
        entity.setExpiryTime(results[1]);
        entity.setPassword(results[3]);

        boolean expiryStatus;

        if (!StringUtils.hasText(entity.getExpiryTime())) {
            expiryStatus = false;
        } else {
            expiryStatus = DateUtils.expried(new Date(Long.parseLong(entity.getExpiryTime())));
        }

        entity.setExpiryStatus(expiryStatus);

        return entity;
    }


    /**
     * 查询是否过期
     *
     * @param cipherText 密文
     * @return 过期状态
     */
    public static Boolean expired(String cipherText) {
        FileSecureEntity fileSecureEntity = decodeToEntity(cipherText);
        if (ObjectUtils.isEmpty(fileSecureEntity)) {
            return true;
        }
        String expiryTime = fileSecureEntity.getExpiryTime();

        //包含分隔符则表示有过期时间
        if (StringUtils.hasText(expiryTime)) {
            Boolean expried = DateUtils.expried(new Date(Long.parseLong(expiryTime)));
            return expried;
        } else {
            return true;
        }

    }
}
